<?php

namespace App\Http\Controllers;

use App\Models\Permission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Route;
use Illuminate\Routing\Exceptions\UrlGenerationException;


class PermissionsController extends Controller
{
    //根据路由刷新权限
    public function flushByRoute(Request $request)
    {
        Artisan::call('route:clear');
        Artisan::call('route:cache');
        collect(Route::getRoutes()->getRoutesByName())->each(function ($item, $key) {
            $description = $item->getActionDescription();
            if(!empty($description)){
                $data['name']       = $description;
                // $data['route']      = $key;
                $data['guard_name'] = $item->action['prefix'];
                try {
                    $data['url'] = route($key, [], false);
                } catch (UrlGenerationException $e) {
                    $data['url'] = '';
                }
                try {
                    Permission::updateOrCreate(['route' => $key], $data);
                } catch (QueryException $e) {
                    return $this->respondError($e->getMessage());
                }
            }
        });
        Artisan::call('db:seed --class=InitRolePermissionSeeder');
        return $this->respondSuccess('刷新成功');
    }
    
    //查
    public function index(Request $request)
    {
        $users = Permission::paginate($request->query('limit'));
        return $this->respondSuccess($users);
    }
}
